import copy
import datetime
import sys
import re

import time
import VAR
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

print("文件开始")

def getData(debug,isNextWeek=False):
    chrome_options = Options()
    # 测试用，不阻塞网页其他资源加载
    # chrome_options.page_load_strategy = 'none'

    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    chrome_options.add_argument("window-size=1200x600")
    d = webdriver.Chrome('/usr/bin/chromedriver', chrome_options=chrome_options)

    #start

    if debug:d.get('file:///'+sys.path[0]+'/test.html')
    else:
        d.get('https://jw.gxjcxy.com/cas/login.action')

        print(d.title)

        # usernameElement = d.find_element_by_id("username").send_keys("value","23104060322")
        # d.find_element_by_id("password").send_keys("value","Wakarimashita!!!")

        print(VAR.USERNAME,VAR.PASSWORD)
        d.execute_script("document.getElementById('username').value = "+VAR.USERNAME)
        d.execute_script("document.getElementById('password').value = "+"'"+str(VAR.PASSWORD)+"'")

        d.find_element_by_id("login").click()

        time.sleep(3)
        print(d.title)
        d.get("http://jw.gxjcxy.com/frame/home/homepage.jsp")

        if isNextWeek:
            print("isNextWeek")
            print(d.find_element_by_id('nextjxz'))
            d.find_element_by_id('nextjxz').click()
            # d.execute_script("document.getElementById('nextjxz').click()")
            # d.execute_script("document.getElementById('nextjxz').click()")

    #  end
    time.sleep(5)
    nowWeekStr = d.find_elements_by_class_name("mykb")[0].find_elements_by_tag_name("td")[0].get_attribute('innerText')
    nowWeek: int
    nowWeek = int(re.sub(r'[^\d]+', '',nowWeekStr[-5:]))


    time.sleep(3)
    # print(d.page_source)
    table = d.find_elements_by_class_name("weeklesson")

    class onlyClass:
        def __init__(self,className,classStart,classEnd,startTime,endTime,teacherName,roomPlace):
            self.className = className
            self.classStart = classStart
            self.classEnd = classEnd
            self.startTime = startTime
            self.endTime = endTime
            self.teacherName = teacherName
            self.roomPlace = roomPlace
    class Day:
        toDayClassTable = []
        def __init__(self,toWeekDay):
            self.toWeekDay = toWeekDay
        def addClass(self,onlyClass):
            self.toDayClassTable.append(onlyClass)

    classTableShape = []
    tablePointer = 0

    newTable = []


    for index in range(7):
        for line in table:
            if str(index+1) == line.get_attribute("id")[7:8]:
                newTable.append(line)

    # print(newTable)

    classBlock = []
    classBlockTable = copy.copy(newTable)

    for day in range(1,8):
        nowTeacherName: str = ""
        toDayClass:list = []
        for child in classBlockTable[:]:

            elementAttributeId = child.get_attribute("id")
            if day != int(elementAttributeId[7:8]):
                break

            bTag = child.find_elements_by_tag_name("b")
            nowForTeacher = bTag[1].get_attribute('innerText') # teacher name
            # if nowTeacherName == '': nowTeacherName=nowForTeacher
            print(nowForTeacher)
            if nowTeacherName != nowForTeacher:
                #personal course filtering
                if className := bTag[0].get_attribute('innerText') == "大学体育Ⅰ":
                    classBlockTable.remove(child)
                    continue

                oneClass: object = {
                                    "class_name":bTag[0].get_attribute('innerText'),
                                    "teacher_name": nowForTeacher,
                                    "start": elementAttributeId[9:11],
                                    "end": '',
                                    "class_room": bTag[3].get_attribute('innerText')}
                toDayClass.append(oneClass)
                nowTeacherName = nowForTeacher
            else:
                oneClass['end'] = elementAttributeId[9:11]
                nowTeacherName = nowForTeacher

            classBlockTable.remove(child)
            print(toDayClass)
            # print(bTag[1].get_attribute('innerText'))
            # print(str(child.find_elements_by_tag_name('li')[1].text))
            # print(elementAttributeId)
        classBlock.append(toDayClass)
            # now handle date
    print(classBlock)

    thisWeekData = open('./thisWeekData.txt','w')
    thisWeekData.write(str({
        "now_week":str(nowWeek),
        "last_update_time":str(time.time()),
        "data":classBlock
    }).replace("'","\""))

    d.close()



getData(False,False)